package com.tianyu.inspection.common.model;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**********************************
 * @Author YSW
 * @Description Http通用工具类
 * @Date 2021/8/25 - 14:22
 **********************************/

public class HttpModel {


    public static String mapToUrlParams(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        if (map == null || map.isEmpty()) {
            return sb.toString();
        }
        for (String key : map.keySet()) {
            sb.append(key).append("=");
            if (StringUtils.isEmpty(map.get(key))) {
                sb.append("&");
            } else {
                String value = map.get(key);
                try {
                    value = URLEncoder.encode(value, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                sb.append(value).append("&");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("name","lisi");
        map.put("age","19");
        System.out.println(mapToUrlParams(map));
    }
}
